import { readFileSync, readdirSync } from "fs";

const attributeMatch = {
  svgTag: /<svg([^>+].*?)>/,
  clearWidthHeight: /(width|height)="([^>+].*?)"/g,
  hasViewBox: /(viewBox="[^>+].*?")/g,
  clearReturn: /(\r)|(\n)/g,
};
let idPerfix = "";

function recursivelyFindSvg(dir: string) {
  const svgRes: string[] = [];
  const dirents = readdirSync(dir, {
    withFileTypes: true, // 将文件作为fs.Dirent对象返回,
    //fs.Dirent 是目录项（可以是文件或目录中的子目录）的表示，通过读取 fs.Dir 返回。 目录项是文件名和文件类型对的组合。
  });
  // console.log(dirents) // { name: 'guanyuwomeng1.svg', [Symbol(type)]: 1 }
  for (const dirent of dirents) {
    if (dirent.isDirectory()) {
      // 判断是否一个目录
      svgRes.push(...recursivelyFindSvg(dir + "/" + dirent.name + "/")); //递归获取svg文件内容
    } else {
      // 读取文件信息并用repalce方法，利用第一步的正则匹配转换svg文件
      const svg = readFileSync(dir + "/" + dirent.name)
        .toString()
        .replace(attributeMatch.clearReturn, "")
        .replace(attributeMatch.svgTag, ($1, $2) => {
          let width: string | number = 0;
          let height: string | number = 0;
          let content = $2.replace(
            attributeMatch.clearWidthHeight,
            (s1: string, s2: string, s3: string) => {
              if (s2 === "width") {
                width = s3;
              } else if (s2 === "height") {
                height = s3;
              }
              return "";
            }
          );
          if (!attributeMatch.hasViewBox.test($2)) {
            content += `viewBox="0 0 ${width} ${height}"`;
          }
          return `<symbol id="${idPerfix}-${dirent.name.replace(
            ".svg",
            ""
          )}" ${content}>`;
        })
        .replace("</svg>", "</symbol>");
      svgRes.push(svg);
    }
  }
  // console.log("🚀 ~ file: svgTagView.js:28 ~ recursivelyFindSvg ~ svgRes", svgRes)

  return svgRes;
}

export const svgTagView = (path: string, perfix = "icon") => {
  if (path === "") return;
  idPerfix = perfix;
  const res = recursivelyFindSvg(path);
  return {
    name: "svg-transform",
    transformIndexHtml(html: any) {
      // transformIndexHtml	转换 index.html 的专用钩子，vite3 独享
      return html.replace(
        "<body>",
        `
          <body>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
              ${res.join("")}
            </svg>
        `
      );
    },
  };
};
